package com.jair.adb;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

public class FixUtils {
	/**
	 * 修复
	 * @param byteArray
	 * @return
	 */
	public static byte[] fixByte(byte[] byteArray){
		int length = byteArray.length;
		boolean fist_D = false;//可以不考虑是第一个D
		boolean flag_D = false;
		//int index_D = 0;
		int count = 0;
		byte[] newByteArray =  new byte[length];
		int new_index = 0;
		for (int i=0 ; i<byteArray.length ;i++) {
			byte c = byteArray[i];
			byte tt = (byte)0x0D;
			if(c  == (byte)0x0D){
				if(fist_D == false){
					fist_D = true;
					newByteArray[new_index] = c;
				}else{
					new_index --;//抵消后面的++
					//index_D = i;
					flag_D = true;
				}
			}else if(flag_D){
				if(c == (byte)0x0A){//
					newByteArray[new_index] = (byte)0x0A;
					flag_D = false;
				}else{
					flag_D = false;
					newByteArray[new_index] = (byte)0x0D;
					new_index++;
					newByteArray[new_index] = c;
				}
			}else{//不是0D,也不是0A
				newByteArray[new_index] = c;
			}
			new_index ++;
		}
		int newArrayL = new_index+1;
		if(newArrayL > length){
			newArrayL = length;
		}
		byte[] newByteArray2 =  new byte[newArrayL];
		System.arraycopy(newByteArray, 0, newByteArray2, 0, newArrayL);
		return newByteArray2;
	}
	
	public static void InputStreamTOByte(InputStream in,File file) throws IOException{
		OutputStream os = new FileOutputStream(file);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[1024];  
        int count = -1;  
        while((count = in.read(data,0,1024)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        byte[] buffer = outStream.toByteArray(); 
        buffer = FixUtils.fixByte(buffer);
        os.write(buffer, 0, buffer.length-1);
        os.close();
    }
	
	/**
	 * 修复直接抓取的截图
	 */
	public static void fixPhotot(){
		
		String dateStr = String.valueOf(new Date().getTime());
		File f = new File("D:\\fixtest"+dateStr+".png");
		try {
			FileInputStream in = new FileInputStream("D:\\test222.png");
			Thread.sleep(3000);
			InputStreamTOByte(in,f);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
